package com.arpa.ntocc.common.service.impl;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONUtil;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.domain.entity.Party;
import com.arpa.ntocc.common.domain.entity.PartyResource;
import com.arpa.ntocc.common.domain.enums.PartyTypeEnum;
import com.arpa.ntocc.common.mapper.PartyResourceMapper;
import com.arpa.ntocc.common.service.IPartyResourceService;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 资源关系业务实现
 *
 * @author liuxr
 * @date 2021/11/15 9:27
 */
@Service
@Log4j2
public class PartyResourceServiceImpl extends ServiceImpl<PartyResourceMapper, PartyResource> implements IPartyResourceService {


    @Override
    public void removeByPartyCode(String partyCode,String groupCode) {
        baseMapper.removeByPartyCode(partyCode,groupCode);
    }



    /**
     * 为组织管理员分配资源
     *
     * @param party     账号标识
     * @author liuxr
     * @date 2021/11/15 15:33
     */
    @Override
    public void assignResourcesToOrganizationAdministrators(Party party) {
        log.info("为组织管理员分配资源,账号信息：{}", JSONUtil.toJsonStr(party));
        if(!party.getPartyType().equals(PartyTypeEnum.GROUP_ADMIN)){
            throw new ServiceException("该账号不是组织管理员，不能进行操作！");
        }
        //获取机构资源列表
        List<PartyResource> groupResourceList = list(Wrappers.lambdaQuery(PartyResource.class)
                .eq(PartyResource::getPartyCode, party.getBranchCode())
                .eq(PartyResource::getGroupCode, party.getBranchCode()));
        log.info("为组织管理员分配资源,所属组织机构资源列表{}", JSONUtil.toJsonStr(groupResourceList));
        if (IterUtil.isNotEmpty(groupResourceList)) {
            for (PartyResource r : groupResourceList) {
                r.setCode(IdUtil.fastSimpleUUID());
                r.setPartyCode(party.getCode());
            }
            saveBatch(groupResourceList);
        }
    }
}
